package com.uinnova.product.eam.service.cj.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binary.core.exception.MessageException;
import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.model.cj.domain.PlanTemplateChapterData;
import com.uino.bean.permission.base.SysUser;
import com.uino.dao.AbstractESBaseDao;
import com.uino.dao.util.ESUtil;
import com.uino.util.exception.LoginException;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.unit.TimeValue;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;

/**
 * @description:
 * @author: Lc
 * @create: 2022-01-05 16:57
 */
@Slf4j
@Component
public class PlanTemplateChapterDataDao extends AbstractESBaseDao<PlanTemplateChapterData, PlanTemplateChapterData> {

    @Override
    public String getIndex() {
        return "uino_cj_plan_template_chapter_data";
    }

    @Override
    public String getType() {
        return getIndex();
    }

    @PostConstruct
    public void init() {
        super.initIndex();
    }

    public Integer saveOrUpdateBatchNoModifyTime(List<PlanTemplateChapterData> list) {
        // JSONArray arr = new JSONArray();
        // arr.addAll(list);
        if (BinaryUtils.isEmpty(list)) {
            return 1;
        }
        list.forEach(obj -> savePreOption(obj));
        JSONArray arr = JSON.parseArray(JSON.toJSONString(list));
        return saveOrUpdateNoModifyTime(arr, true);
    }

    public Integer saveOrUpdateNoModifyTime(JSONArray list, boolean isRefresh) {
        Integer flag = 1;
        BulkRequest bulkRequest = new BulkRequest();
        SysUser currentUser = null;
        try {
            currentUser = SysUtil.getCurrentUserInfo();
        } catch (LoginException e) {
            log.debug("无法获取当前登陆用户，该持久化信息可能会缺失[创建/修改]人信息和domain域信息不对的问题");
        }
        for (int i = 0; (!list.isEmpty() && i < list.size()); i++) {
            JSONObject obj = list.getJSONObject(i);
            fillPreferencesInfo(obj, currentUser);
            UpdateRequest uRequest = this.getUpdateRequest(obj.get("id").toString());
            uRequest.doc(obj);
            uRequest.docAsUpsert(true);
            bulkRequest.add(uRequest);
        }
        bulkRequest.timeout(TimeValue.timeValueMinutes(2));
        if (isRefresh) {
            bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        }
        try {
            BulkResponse bulkResponse = getClient().bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                flag = 0;
                log.error(bulkResponse.buildFailureMessage());
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            flag = 0;
            throw new MessageException(e.getMessage());
        }
        return flag;
    }

    protected void fillPreferencesInfo(JSONObject obj, SysUser currentUser) {
        if (obj == null) {
            return;
        }
        String userLoginCode = currentUser == null ? "system" : currentUser.getLoginCode();
        Long nowTime = BinaryUtils.isEmpty(obj.get("modifyTime")) ? ESUtil.getNumberDateTime() : Long.parseLong(obj.get("modifyTime").toString());
        if (!obj.containsKey("id") || BinaryUtils.isEmpty(obj.get("id"))) {
            // add-data处理
            obj.put("id", ESUtil.getUUID());
            obj.put("createTime", nowTime);
            if (!obj.containsKey("creator") || BinaryUtils.isEmpty(obj.get("creator"))) {
                obj.put("creator", userLoginCode);
            }
        } else {
            // update-data处理
            if (!obj.containsKey("createTime") || BinaryUtils.isEmpty(obj.get("createTime"))) {
                obj.put("createTime", nowTime);
            }
        }
        obj.put("modifyTime", nowTime);
        obj.put("modifier", userLoginCode);
        if (!obj.containsKey("domainId") || BinaryUtils.isEmpty(obj.get("domainId"))) {
            obj.put("domainId", currentUser != null ? currentUser.getDomainId() : 1L);
        }
    }


}
